import { useEffect, useRef } from 'react';
import { View, Text, ScrollView, StyleSheet, Pressable, DeviceEventEmitter } from 'react-native';
import { StatusBar } from 'expo-status-bar';
import AntDesign from '@expo/vector-icons/AntDesign';
import MaterialIcons from '@expo/vector-icons/MaterialIcons';
import Decimal from 'decimal.js'

import { useSetState, useCurrent } from '../../common/hooks/index'
import { RootView, Header } from '../../components/Layout';
import { CStyle, CFlex, CColor } from '../../constant/css'
import ProductServer from '../../common/service/ProductServer';
import CommonServer from '../../common/service/CommonServer';
import * as FORM from "../../components/Form"
import util from '../../common/utils/util';
import ImageView from '../../components/ImageView';
import Constant from '../../constant/Constant';

// * 商品详情
export default function ProductDetail(props) {
    const params = util.ExpoRouter.useLocalSearchParams()
    console.log('ProductDetail :>> ', JSON.stringify(params))

    const [state, setState] = useSetState({
        data: {},
        images: [],
        putRecord: [],
        putTotal: 0,
        outRecord: [],
        outTotal: 0,
    })
    const _ref = useRef({})

    useEffect(() => {
        loadProductDetail()

        _ref.current.refreshProduct = DeviceEventEmitter.addListener('refreshProduct', () => {
            loadProductDetail()
        })
        return () => {
            _ref.current?.refreshProduct?.remove?.()
        }
    }, [])

    const loadProductDetail = async () => {
        const [err, res] = await ProductServer.getProductById({ pId: params.id })
        if (err) {
            util.ExpoRouter.router.back()
            return util.showError(err)
        }
        const [imageErr, imageRes] = await CommonServer.loadImageByRefGuid({ refGuid: params.id, type: 1 })
        const result = res?.data || {}
        const images = []

        result.cover && images.push({ url: result.cover })
        imageRes?.data?.length && images.push(...imageRes.data)

        setState({
            data: res?.data || {},
            images
        })

        loadRecord()
    }

    const loadRecord = async () => {
        const [err, res] = await ProductServer.loadRecordByPId({ pId: params.id })
        if (err) return util.showError(err)
        const { out = [], put = [] } = res?.data || {}
        const outTotal = out.reduce((total, _) => (total = total.add(new Decimal(_.sum))) && total, new Decimal(0))

        const putTotal = put.reduce((total, _) => (total = total.add(new Decimal(_.sum))) && total, new Decimal(0))
        setState({
            putRecord: put,
            outRecord: out,
            putTotal: putTotal.toString(),
            outTotal: outTotal.toString(),
        })
    }

    const renderHeader = () =>
        <>
            <Pressable style={[styles.back, { left: 8 }]} onPress={() => util.ExpoRouter.router.back()}>
                <AntDesign name="arrowleft" size={24} color={CColor.White} />
            </Pressable>
            <Pressable style={[styles.back, { right: 8 }]} onPress={() => {
                util.ExpoRouter.router.push('/product/addOrEdit')
                util.ExpoRouter.router.setParams({ id: params.id })
            }}>
                <MaterialIcons name="edit" size={18} color={CColor.White} />
            </Pressable>
            <Pressable style={[styles.back, { right: 58 }]} onPress={() => {
                util.ExpoRouter.router.push('/stock/putAndOut')
                util.ExpoRouter.router.setParams({ type: 1, data: JSON.stringify(state.data) })
            }}>
                <AntDesign name="minus" size={24} color={CColor.White} />
            </Pressable>
            <Pressable style={[styles.back, { right: 108 }]} onPress={() => {
                util.ExpoRouter.router.push('/stock/putAndOut')
                util.ExpoRouter.router.setParams({ type: 0, data: JSON.stringify(state.data) })
            }}>
                <AntDesign name="plus" size={24} color={CColor.White} />
            </Pressable>
        </>

    const renderImage = () =>
        <ImageView
            height={320}
            urls={state.images}
        />

    const renderBaseInfo = () => {
        const { data } = state
        const list = [
            {
                label: 'IP：',
                value: 'pIp',
                line: true,
                labelComponent: () => null,
                valueComponent: () =>
                    <View style={[CStyle.tag]}>
                        <Text style={{ color: CColor.White, fontSize: 12 }}>{data.pIp}</Text>
                    </View>
            },
            {
                label: '商品：',
                labelComponent: () => null,
                value: 'name',
                line: true,
                textStyle: {
                    color: CColor.Black,
                    fontWeight: 'bold',
                }
            },
            {
                label: '整盒价：',
                value: 'boxPrice',
                unit: '￥',
                textStyle: {
                    color: CColor.Red,
                    fontWeight: 'bold',
                },
            },
            {
                label: '售价：',
                value: 'sellPrice',
                unit: '￥',
                textStyle: {
                    color: CColor.Red,
                    fontWeight: 'bold',
                },
            },
            {
                label: '库存：',
                value: 'stock',
                unit: '个',
                textStyle: {
                    color: CColor.Black,
                    fontWeight: 'bold',
                },
            },
            {
                label: '进价：',
                value: 'buyPrice',
                unit: '￥',
                textStyle: {
                    color: CColor.Red,
                    fontWeight: 'bold',
                },
            },
            {
                label: '入库时间：',
                value: 'enterDate',
                valueFunc: () => util.dayjs(data.enterDate).format('YYYY-MM-DD HH:mm'),
                line: true,
                textStyle: {
                    color: CColor.Black,
                },
            },
            {
                label: '分类：',
                value: 'categoryDesc',
                line: true,
            },
            {
                label: '货源：',
                value: 'sourceDesc',
                valueComponent: () =>
                    <View style={[CStyle.tag, { backgroundColor: CColor.Origin }]}>
                        <Text style={{ color: CColor.White, fontSize: 12 }}>{data.sourceDesc}</Text>
                    </View>
            },
            {
                label: '状态：',
                value: 'statusDesc',
                valueComponent: () =>
                    <View style={[CStyle.tag, { backgroundColor: CColor.Header }]}>
                        <Text style={{ color: CColor.White, fontSize: 12 }}>{data.statusDesc}</Text>
                    </View>
            },
        ]
        return (
            <FORM.FormItem
                data={data}
                list={list}
            />
        )
    }

    const renderRecordItem = (item) =>
        <View key={item.guid} style={[styles.border, { marginBottom: 10, padding: 5 }]}>
            <Text style={{ fontSize: 12, color: CColor.Black }}>{util.dayjs(item.orderDate).format('YYYY-MM-DD HH:mm')}</Text>
            <View style={[CFlex.row, CFlex.sc, { marginTop: 5 }]}>
                <Text>以</Text>
                <Text style={{ color: CColor.Red, fontWeight: 'bold', fontStyle: 'italic' }}> ￥{item.price} </Text>
                <View style={[CStyle.tag, { backgroundColor: item.type ? CColor.Origin : CColor.Black, marginHorizontal: 2 }]}>
                    <Text style={{ color: CColor.White }}>{item.type ? '成交' : '买入'}</Text>
                </View>
                <Text> <Text style={{ color: CColor.Blue, fontWeight: 'bold' }}>{item.total}</Text> 件 </Text>
            </View>
            <View style={[CFlex.row, CFlex.ee]}>
                <Text style={{ color: CColor.Red, fontStyle: 'italic', fontWeight: 'bold' }}>{`${item.type ? '+' : '-'}${item.sum}￥`}</Text>
            </View>
        </View>

    const renderOutView = () => {
        const { outRecord, outTotal } = state
        return (
            <View style={{ marginTop: 10 }}>
                <FORM.Label
                    title='成交记录'
                    style={{ fontWeight: 'bold' }}
                    showRequired={false}
                />
                <View style={styles.radius}>
                    {
                        outRecord.length ?
                            <View>
                                {
                                    outRecord.map(item => renderRecordItem(item))
                                }
                                <View style={[CFlex.row, CFlex.ee]}>
                                    <Text style={{ color: CColor.Red, fontStyle: 'italic', fontWeight: 'bold' }}>{`+${outTotal}￥`}</Text>
                                </View>
                            </View>
                            :
                            <View style={CFlex.cc}>
                                <FORM.ExpoImage style={{ width: 150, height: 150 }} contentFit="cover"
                                    source={require('./../../assets/404.svg')} />
                                <Text style={{ color: CColor.Black, marginBottom: 10 }}>暂无记录</Text>
                            </View>
                    }

                </View>
            </View>
        )
    }

    const renderInView = () => {
        const { putRecord, putTotal } = state
        return (
            <View style={{ marginTop: 10 }}>
                <FORM.Label
                    title='进货记录'
                    style={{ fontWeight: 'bold' }}
                    showRequired={false}
                />
                <View style={styles.radius}>
                    {
                        putRecord.length ?
                            <View>
                                {
                                    putRecord.map(item => renderRecordItem(item))
                                }
                                <View style={[CFlex.row, CFlex.ee]}>
                                    <Text style={{ color: CColor.Red, fontStyle: 'italic', fontWeight: 'bold' }}>{`-${putTotal}￥`}</Text>
                                </View>
                            </View>
                            :
                            <View style={CFlex.cc}>
                                <FORM.ExpoImage style={{ width: 150, height: 150 }} contentFit="cover"
                                    source={require('./../../assets/404.svg')} />
                                <Text style={{ color: CColor.Black, marginBottom: 10 }}>暂无记录</Text>
                            </View>
                    }

                </View>
            </View>
        )
    }

    return (
        <View style={styles.container}>
            <StatusBar translucent />
            {renderHeader()}
            <ScrollView
                showsVerticalScrollIndicator={false}
            >
                {renderImage()}
                <View style={{ paddingHorizontal: 12, marginBottom: 20 }}>
                    {renderBaseInfo()}
                    {renderOutView()}
                    {renderInView()}
                </View>
            </ScrollView>
        </View>
    )
}

const styles = StyleSheet.create({
    container: {
        flex: 1
    },
    back: {
        position: 'absolute',
        top: 40,
        zIndex: 999,
        width: 40,
        height: 40,
        borderRadius: 50,
        ...CFlex.cc,
        backgroundColor: 'rgba(0,0,0,0.5)'
    },
    radius: {
        marginTop: 10,
    },
    border: {
        borderWidth: 1,
        borderColor: CColor.Black,
        borderRadius: 5,
    },
})